<template>
  <div class="strategyAnalyse-page app-container">
    <div v-if="strategy_dels.investDetial" class="head">
      <div v-if="!strategyType" class="chunk title">
        <div class="product">
          <h3>{{strategy_dels.investDetial.investChildrenName}}</h3>
          <p style="margin-top: 14px;">
            单位净值：<span style="font-size: 22px;color: #c00;">{{strategy_dels.investDetial.initialNetworth}}</span>
            <span style="padding-left: 80px;"></span>
            收益率：
            <span v-if="typeof strategy_dels.investDetial.investIncomeRate == 'number'" :class="strategy_dels.investDetial.investIncomeRate>=0?'positiveFc':'negativeFc'">{{strategy_dels.investDetial.investIncomeRate}}%</span>
            <span v-else>/</span>
          </p>
        </div>
        <div style="font-size: 13px;" class="info">
          <div style="padding-left: 30%;">
            <div class="fromLine">
              <div class="label">{{strategy_dels.investManage&&strategy_dels.investManage.investAdviser?'所属投顾：':'母账号：'}}</div>
              <div class="fromLine-content">
                {{strategy_dels.investManage.investAdviser ? strategy_dels.investManage.investAdviser : strategy_dels.investManage.investAccount}}
              </div>
            </div>
            <div class="fromLine">
              <div class="label">操作账号：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.investAccount}}</div>
            </div>
            <div class="fromLine">
              <div class="label">策略名称：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.strategyName}}</div>
            </div>
          </div>
        </div>
        <div style="font-size: 13px;" class="info2">
          <div style="padding-left: 30%;">
            <div class="fromLine">
              <div class="label">投资状态：</div>
              <div class="fromLine-content">
                <span class="circular" :class="!strategy_dels.investDetial.investStatus?'s-warning':strategy_dels.investDetial.investStatus==1?'s-success':'s-error'"></span> {{strategy_dels.investDetial.investStatus | investStatusFilter}}
              </div>
            </div>
            <div class="fromLine">
              <div class="label">初始权益：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.initialMoney}} 万元</div>
            </div>
            <div class="fromLine">
              <div class="label">初始份额：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.initialShare}}</div>
            </div>
          </div>
        </div>
        <div style="font-size: 13px;" class="info2">
          <div style="padding-left: 30%;">
            <div class="fromLine">
              <div class="label">对标指数：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.investIndexText}}</div>
            </div>
            <div class="fromLine">
              <div class="label">开始时间：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.investStarttime | parseTime}}</div>
            </div>
            <div class="fromLine">
              <div class="label">结束时间：</div>
              <div class="fromLine-content">{{strategy_dels.investDetial.investEndtime | parseTime}}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="chunk operation from-alignCenter">
          <el-form ref="formData" :inline="true" label-width="82px" :model="formData">
            <el-form-item label="对比指标：" prop="types">
              <indexSelectTree
                style="margin: 0 30px 0 10px"
                :indexType.sync="formData.types"
                :clearable="false"
                :width="280"
              ></indexSelectTree>
            </el-form-item>
            <el-form-item style="margin-left: 20px">
              <el-button type="primary" @click="saveParamsHandle">保存应用</el-button>
              <el-button @click="refresh">重置</el-button>
            </el-form-item>
          </el-form>
      </div>
    </div>

    <!-- 悬浮头部 -->
    <div v-show="scrollCard" class="scrollCard from-alignCenter">
      <el-form ref="formData" :inline="true" label-width="82px" :model="formData">
        <el-form-item label="对比指标：" prop="types">
          <indexSelectTree
            style="margin: 0 30px 0 10px"
            :indexType.sync="formData.types"
            :clearable="false"
            :width="280"
          ></indexSelectTree>
        </el-form-item>
        <el-form-item style="margin-left: 20px">
          <el-button type="primary" @click="saveParamsHandle">保存应用</el-button>
          <el-button @click="refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="column">
      <span>历史走势图</span>
      <i class="el-icon el-icon-d-arrow-right" :class="{'openChunk': showChunk1}" @click="showChunk1=!showChunk1" />
    </div>
    <div v-show="showChunk1" class="showChunk">
      <div class="line">
        <el-date-picker
          style="margin-left: 50%;"
          v-model="chart_date"
          type="daterange"
          align="right"
          unlink-panels
          :clearable="false"
          value-format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </div>
      <chart v-if="strategy_dels.investDetial.investChildrenName&&list_netWorthLine.length&&list_risk_chart.length" :y-name="strategy_dels.investDetial.investChildrenName"
      :data="list_netWorthLine" :data22="list_risk_chart" :contrastIndex_obj="contrastIndex_obj" :contrastIndexRisk_obj="contrastIndexRisk_obj"
      :height="280" width="100%" />
      <div v-else style="height:400px;"></div>
    </div>

    <!-- 历史配置设置 -->
    <div v-if="strategyType" class="column">
      <span>历史配置设置</span>
      <i class="el-icon el-icon-d-arrow-right" :class="{'openChunk': showChunk5}" @click="showChunk5=!showChunk5" />
    </div>
    <div v-if="strategyType" v-show="showChunk5" class="showHistoryChunk">
      <div v-show="strategyType==1" class="historyChunk">
        <el-table
          v-loading="listLoading"
          :data="strategyPortfolioDetials"
          stripe fit
          size="mini"
          :cell-style="{padding: '8px 0'}"
          :header-cell-style="{background:'#dcedff',color:'#32639d'}"
          style="width: 100%;margin-top:20px"
        >
          <el-table-column prop="strategyName" label="产品名称"></el-table-column>
          <el-table-column prop="marketValue" label="最初持仓市值(万元)" align="center"></el-table-column>
          <el-table-column prop="marketValue" label="实际持仓市值(万元)" align="center"></el-table-column>
          <el-table-column prop="weight" label="权重" align="center"></el-table-column>
          <el-table-column prop="" label="实际年化收益率" align="center">
            <template slot-scope="{$index}">
              <span v-if="netWorthDetialBeanList[$index]&&netWorthDetialBeanList[$index].yearAnnualizedincomeRate" :class="netWorthDetialBeanList[$index].yearAnnualizedincomeRate>=0?'positiveFc':'negativeFc'">
                {{ netWorthDetialBeanList[$index].yearAnnualizedincomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="实际年化波动率" align="center">
            <template slot-scope="{$index}">
              <span v-if="netWorthDetialBeanList[$index]&&netWorthDetialBeanList[$index].yearAnnualfluctuationsRate">
                {{ netWorthDetialBeanList[$index].yearAnnualfluctuationsRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="enterTime" label="进入日期" align="center"></el-table-column>
        </el-table>
      </div>
      <div v-show="strategyType==3" class="historyChunk">
        <historyChart v-if="netWorthDetialBeanList.length" id="historyChart" :data1="netWorthDetialBeanList" :data2="strategyPortfolio" height="300px" width="100%" />
      </div>
      <div v-show="strategyType==3" class="historyChunk">
        <el-table
          v-loading="listLoading"
          :data="strategyPortfolioDetials"
          stripe fit
          size="mini"
          :cell-style="{padding: '8px 0'}"
          :header-cell-style="{background:'#dcedff',color:'#32639d'}"
          style="width: 100%;margin-top:20px"
        >
          <el-table-column prop="strategyName" label="产品名称"></el-table-column>
          <el-table-column prop="marketValue" label="预期年化收益率" align="center">
            <template slot-scope="{$index}">
              <span v-if="netWorthDetialBeanList[$index]&&netWorthDetialBeanList[$index].yearAnnualizedincomeRate" :class="netWorthDetialBeanList[$index].yearAnnualizedincomeRate>=0?'positiveFc':'negativeFc'">
                {{ netWorthDetialBeanList[$index].yearAnnualizedincomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="marketValue" label="预期年化波动率" align="center">
            <template slot-scope="{$index}">
              <span v-if="netWorthDetialBeanList[$index]&&netWorthDetialBeanList[$index].yearAnnualfluctuationsRate">
                {{ netWorthDetialBeanList[$index].yearAnnualfluctuationsRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="实际年化收益率" align="center">
            <template slot-scope="{$index}">
              <span v-if="netWorthDetialBeanList[$index]&&netWorthDetialBeanList[$index].yearAnnualizedincomeRate" :class="netWorthDetialBeanList[$index].yearAnnualizedincomeRate>=0?'positiveFc':'negativeFc'">
                {{ netWorthDetialBeanList[$index].yearAnnualizedincomeRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="" label="实际年化波动率" align="center">
            <template slot-scope="{$index}">
              <span v-if="netWorthDetialBeanList[$index]&&netWorthDetialBeanList[$index].yearAnnualfluctuationsRate">
                {{ netWorthDetialBeanList[$index].yearAnnualfluctuationsRate }}%
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="enterTime" label="进入日期" align="center"></el-table-column>
        </el-table>
      </div>
    </div>

    <div class="column">
      <span>收益风险指标</span>
      <i class="el-icon el-icon-d-arrow-right" :class="{'openChunk': showChunk2}" @click="showChunk2=!showChunk2" />
    </div>
    <div v-show="showChunk2" class="showChunk">
      <el-table
        v-loading="listLoading_riskIndicators"
        :data="list_riskIndicators"
        fit
        size="mini"
        style="width: 100%;margin-top:20px"
        :cell-style="{padding: '8px 0'}"
        :cell-class-name="tableRowClassName"
        :header-cell-style="{color:'#333'}"
      >
        <el-table-column type="index" width="200" :index="titleHandle"></el-table-column>
        <el-table-column :prop="key" :label="add_column_list[key]" v-for="(item, key) in list_riskIndicators[0]" :key="key" align="center"></el-table-column>
      </el-table>
    </div>
    <div class="column">
      <span>历史净值</span>
      <i class="el-icon el-icon-d-arrow-right" :class="{'openChunk': showChunk3}" @click="showChunk3=!showChunk3" />
    </div>
    <div v-show="showChunk3" class="showChunk">
      <el-table
        v-loading="listLoading_netWorth"
        :data="list_netWorth"
        stripe fit
        size="mini"
        :cell-style="{padding: '8px 0'}"
        :header-cell-style="{background:'#dcedff',color:'#32639d'}"
        style="width: 100%;margin-top:20px"
      >
        <el-table-column type="index" label="序号" align="center" width="60"></el-table-column>
        <el-table-column v-if="!strategyType" prop="adviserName" label="投顾名称" align="center" width="100"></el-table-column>
        <el-table-column v-if="!strategyType" prop="strategyName" label="策略名称" width="280"></el-table-column>
        <el-table-column prop="networthTime" label="净值日期" align="center">
          <template slot-scope="{row}">
            <span>{{row.networthTime | parseTime}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="networthValue" label="单位净值" align="center"></el-table-column>
        <el-table-column prop="networthValue" label="累计净值" align="center"></el-table-column>
        <el-table-column prop="networthValue" label="复权累计净值" align="center"></el-table-column>
        <el-table-column prop="calmarRate" label="涨跌幅" align="center"></el-table-column>

        <el-table-column v-if="!strategyType" label="操作" width="240">
          <template slot-scope="{row}">
            <el-button class="filter-item" size="mini" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleUpdate(row)">
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="total_netWorth>0" style="padding-bottom: 0;" :total="total_netWorth" :page.sync="listQuery.pageCurrent" :limit.sync="listQuery.limit" @pagination="getNetWorth" />
    </div>

    <div class="column">
      <span>历史月度表现</span>
      <i class="el-icon el-icon-d-arrow-right" :class="{'openChunk': showChunk4}" @click="showChunk4=!showChunk4" />
    </div>
    <div v-show="showChunk4" class="showChunk">
      <div class="line" style="margin-top: 20px;">
        <div class="showMonth">
          <div class="round round1"></div>
          {{ strategy_dels.investDetial.investChildrenName }}
        </div>
        <div class="showMonth">
          <div class="round round2"></div>
          <el-select style="width: 130px;" v-model="month_contrast" size="mini" placeholder="请选择" @change="monthContrastHandle">
            <el-option
              v-for="item in one_contrastOptions_list"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
      </div>
      <!-- listLoading_netWorth -->
      <el-table
        v-loading="listLoading_monthNetWorth"
        :data="list_showMonth"
        stripe fit
        size="mini"
        :cell-class-name="showMonthTableClassName"
        :cell-style="{padding: '8px 0'}"
        :header-cell-style="{background:'#dcedff',color:'#32639d'}"
        style="width: 100%;margin-top:20px"
      >
        <el-table-column prop="0.year" label="年份" width="100" align="center"></el-table-column>
        <el-table-column :prop="`${i-1+''}`" :label="`${i}月`" align="center" v-for="i in 12" :key="i">
          <template slot-scope="scope">
            <span v-if="scope.row[i-1].monthIncrease!=null" :class="scope.row[i-1].monthIncrease>=0?'positiveFc':'negativeFc'">
              {{scope.row[i-1].monthIncrease}}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column prop="12.monthIncrease" label="YTD" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row[12].monthIncrease!=null" :class="scope.row[12].monthIncrease>=0?'positiveFc':'negativeFc'">
              {{scope.row[12].monthIncrease}}%
            </span>
            <span v-else>--</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="line" style="margin-top: 20px;">
        <el-button-group>
          <el-button size="small" :type="monthChartBtn?'':'primary'" @click="monthChartBtn=0">月度回报</el-button>
          <el-button size="small" :type="monthChartBtn?'primary':''" @click="monthChartBtn=1">收益分布</el-button>
        </el-button-group>
      </div>
      <div class="month-chartContent">
        <div class="mChunk">
          <showmonth-chart v-if="strategy_dels.investDetial.investChildrenName&&monthChartBtn" id="showmonthChart" :name_contrast="name_contrast" :month_contrast="month_contrast" :y-name="strategy_dels.investDetial.investChildrenName" :data="list_monthNetWorthLine" height="350px" width="100%" />
          <month-return-chart v-else-if="strategy_dels.investDetial.investChildrenName&&(!monthChartBtn)" id="monthReturnChart" :name_contrast="name_contrast" :month_contrast="month_contrast" :y-name="strategy_dels.investDetial.investChildrenName" :data="list_monthNetWorthDistributed" :height="400" width="100%" />
        </div>
        <div class="mChunk">
          <el-table
            v-if="strategy_dels.investDetial.investChildrenName&&monthChartBtn"
            v-loading="findNetWorthExtendByStrategyId2_loading"
            :data="list_showMonth_profit"
            stripe fit
            size="mini"
            :cell-style="{padding: '6px 0'}"
            :header-cell-style="{background:'#dcedff',color:'#32639d'}"
            style="width: 100%;margin-top:20px"
            :key="list_showMonth_key"
          >
            <el-table-column prop="" label="" align="center">
              <template slot-scope="scope">
                <span>{{list_showMonth_profit_column1[scope.$index].name}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="1" :label="strategy_dels.investDetial.investChildrenName" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.incomeRate||scope.row.incomeRate==0" :class="scope.row.incomeRate>=0?'positiveFc':'negativeFc'">{{ scope.row.incomeRate }}%</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="2" :label="name_contrast" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.growth" :class="scope.row.growth>0?'positiveFc':'negativeFc'">{{ scope.row.growth }}%</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          <el-table
            v-show="strategy_dels.investDetial.investChildrenName&&(!monthChartBtn)"
            v-loading="getMonthNetWorthDetial_loading"
            :data="list_table_getMonthNetWorthDetial"
            stripe fit
            size="mini"
            :cell-style="{padding: '6px 0'}"
            :header-cell-style="{background:'#dcedff',color:'#32639d'}"
            style="width: 100%;margin-top:20px"
          >
            <el-table-column prop="date" label="净值日期" align="center"></el-table-column>
            <el-table-column prop="netWorthMonth" label="单位净值" align="center"></el-table-column>
            <el-table-column prop="netWorthRestorationMonth" label="累计净值" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.netWorthRestorationMonth"><span style="color:#F00;">*</span>{{ scope.row.netWorthRestorationMonth }}</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
            <el-table-column prop="monthIncrease" label="月涨跌幅" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.monthIncrease||scope.row.monthIncrease==0" :class="scope.row.monthIncrease>=0?'positiveFc':'negativeFc'">{{ scope.row.monthIncrease }}%</span>
                <span v-else>--</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="monthNetWorthDetial_total>0&&strategy_dels.investDetial&&strategy_dels.investDetial.investChildrenName&&(!monthChartBtn)" style="padding-bottom: 0;"
            :total="monthNetWorthDetial_total"
            :page.sync="monthNetWorthDetial_listQuery.pageCurrent"
            :limit.sync="monthNetWorthDetial_listQuery.limit" @pagination="getMonthNetWorthDetial"
          />
        </div>
      </div>
    </div>
    <div style="height: 150px;"></div>
  </div>
</template>

<script>
import { queryAllIndexType, saveUserSelectType, findIndexByIndexTypeAndIndexTime, getIndexRiskByIndexTypeAndTime,
  getMonthlyIndex, findIndexMaxDown, findTimeScopeGrowth } from '@/api/policyManage'
import { getRiskInditor, getMonthlyIncrease, getInvestMonthNetWorthDetial, getMonthInvestNetWorthDistributed, monthlyNetworthHistogram,
  findNetWorthBySegment, findNetWorthByPage, getInvestStrategyDetial, findRealityInvestNetWorthByStrategyId, findMaxDown } from '@/api/afterInvest'
import Chart from '@/components/Charts/lineEcharts_netWorthAnalysis1.vue'
import showmonthChart from '@/components/Charts/lineEcharts_netWorthShowMonth.vue'
import monthReturnChart from '@/components/Charts/barEcharts_monthReturn.vue'
import historyChart from '@/components/Charts/netWorthAnalysis_historty.vue'
import Pagination from '@/components/Pagination'
import { parseTime, deepClone } from '@/utils'
import indexSelectTree from "@/components/investComn/indexSelectTree.vue";
export default {
  name: 'NetWorthAnalysis',
  components: { Chart, Pagination, showmonthChart, monthReturnChart, historyChart,indexSelectTree },
  data() {
    return {
      investId: '',
      contrastOptions: [],
      contrastOptions_obj: {},
      one_contrastOptions_list: [],
      contrastIndex_obj: {}, // 收益走势对比指数
      contrastIndexRisk_obj: {}, // 风险概括对比指数
      scrollCard: false,
      formData: {
        types: []
      },

      showChunk1: true,
      showChunk2: true,
      showChunk3: true,
      showChunk4: true,
      showChunk5: true,

      strategyId: '',
      userId: '',
      strategyType: 0, // 区分策略和组合策略
      listLoading_netWorth: false,
      listQuery: {
        pageCurrent: 1,
        limit: 10
      },
      list_netWorth: [], //历史净值
      total_netWorth: 0,
      strategy_dels: {
        investDetial: {
          strategyName: ''
        },
        investManage: {
          investAdviser: ''
        }
      }, //策略详情

      listLoading_riskIndicators: false,
      list_riskIndicators: [], // 收益风险指标
      _list_riskIndicators: [], // 保存基础 收益风险指标
      riskIndicators_columnLabel: {
        'annualizedIncomeRate': '年化收益',
        'annualFluctuationsRate': '年化波动',
        'sharpeRate': '夏普比率',
        'maximumDrawdownRate': '最大回撤',
        'calmarRate': '卡玛比率',
        'maxBackIncomDay': '最大回补天数'
      },
      add_column_list: [],

      list_netWorthLine: [], //净值曲线
      chart_date: [],
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },

      // todo 月度表现
      listLoading_monthNetWorth: false,
      month_contrast: undefined,
      name_contrast: '',
      list_showMonth: [],
      _list_showMonth: [],
      monthChartBtn: 0,
      list_showMonth_profit: [],
      list_showMonth_key: 0,
      list_showMonth_profit_column1: [
        { id: 99, name: '成立以来' },
        { id: 0, name: '今年以来' },
        { id: 1, name: '近1月' },
        { id: 3, name: '近3月' },
        { id: 6, name: '近6月' },
        { id: 12, name: '近1年' },
        { id: 24, name: '近2年' },
        { id: 36, name: '近3年' },
      ],
      list_monthNetWorthLine: [], // 收益分布
      findNetWorthExtendByStrategyId2_loading: false, // 收益分布 列表loading
      list_monthNetWorthDistributed: [], // 月度回报 echart
      list_table_getMonthNetWorthDetial: [], // 月度回报 列表
      getMonthNetWorthDetial_loading: false, // 月度回报 列表loading
      monthNetWorthDetial_listQuery: { // 月度回报 分页
        pageCurrent: 1,
        limit: 10
      },
      monthNetWorthDetial_total: 0,

      // 风险概括
      listLoading_risk: false,
      list_risk_chart: [],

      // 策略组合
      listLoading: false,
      portfolioId: undefined,
      strategyPortfolio: {}, // 历史配置设置用
      strategyPortfolioDetials: [],
      portfolioNetWorthBean: [], // 123..月
      netWorthDetialBeanList: [], // 子策略数据
    }
  },
  watch: {
    'formData.types': {
      handler(newVal, oldVal) {
        if(newVal.length > 4 || newVal.length == 0) {
          this.$notify({
            message: newVal.length ? '最多选择4个对比指标' : '最少选择1个对比指标',
            type: 'warning',
            duration: 2000
          })
          this.$nextTick(() => {
            this.formData.types = oldVal
          })
        }else {
          if(Object.keys(this.contrastOptions_obj).length) {
            this.one_contrastOptions_list = []
            newVal.forEach(item => {
              this.one_contrastOptions_list.push({
                id: item,
                name: this.contrastOptions_obj[item]
              })
            })
            this.month_contrast = newVal[0]
            if(this.chart_date.length) this.monthContrastHandle(newVal[0])
          }
        }
      },
      deep: true
    },
    month_contrast(val) {
      if(val) {
        this.name_contrast = this.contrastOptions_obj[val] // 月度表现头部修改
      }
    },
    chart_date: {
      handler(date, oldDate) {
        if(oldDate.length !== 0) {
          this.list_risk_chart = [] //防止一条数据变化就立马渲染
          this.list_netWorthLine = []
          this.getnetWorthLine(date[0], date[1])
          this.findMaxDown(date[0], date[1])
        }
      }
    }
  },
  filters: {
    investStatusFilter(i) {
      const list = ['未开始', '进行中', '已终止']
      return list[i]
    }
  },
  created() {
    this.strategyId = this.$route.query.id
    this.investId = this.$route.query.investId
    this.userId = this.$route.query.userId
    this.strategyType = this.$route.query.strategyType

    Promise.all([this.getStrategyByid(this.strategyId)]).then(res => {
      this.findIndexByIndexTypeAndIndexTime(res[0][0], res[0][1], this.formData.types)
      this.findIndexMaxDown(res[0][0], res[0][1], this.formData.types)
      this.findNetWorthExtendByStrategyId2(this.strategyId)
    })

    this.getNetWorth()
    this.queryAllIndexType()
    this.getMonthNetWorth(this.strategyId)
    this.getMonthNetWorthLine(this.strategyId)
    this.getMonthNetWorthDistributed(this.strategyId)
    this.getMonthNetWorthDetial(this.strategyId)

    window.addEventListener('scroll', this.watchScroll)
  },
  methods: {
    watchScroll() {
      if(document.documentElement.scrollTop >= 318) {
        this.scrollCard = true
      }else {
        this.scrollCard = false
      }
    },
    showMonthTableClassName({ rowIndex, columnIndex }) {
      if(columnIndex === 0 && rowIndex%2 === 0) {
        return 'showMonthyearBorder0'
      }else if(columnIndex === 0 && rowIndex%2 !== 0) {
        return 'showMonthyearBorder1'
      }
    },
    tableRowClassName({ columnIndex }) {
      if (columnIndex === 0) {
        return 'title-row'
      } else if (columnIndex === 1) {
        return 'cell-row-0'
      } else if (columnIndex === 2) {
        return 'cell-row-1'
      } else if (columnIndex === 3) {
        return 'cell-row-2'
      } else if (columnIndex === 4) {
        return 'cell-row-3'
      } else if (columnIndex === 5) {
        return 'cell-row-4'
      } else if (columnIndex === 6) {
        return 'cell-row-5'
      } else if (columnIndex === 7) {
        return 'cell-row-6'
      }
      return ''
    },
    titleHandle(i) {
      const key_list = Object.keys(this.riskIndicators_columnLabel)
      return this.riskIndicators_columnLabel[key_list[i]]
    },
    handleUpdate(row) {},
    // 收益风险指标
    getriskIndicators() {
      getRiskInditor({
        id: this.strategyId
      }).then(res => {
        this.listLoading_riskIndicators = false
        console.log('风险指标', res)
        this.add_column_list.push(this.strategy_dels.investDetial.investChildrenName)
        Object.keys(this.riskIndicators_columnLabel).forEach((key, i) => {
          const val = res.body[key]
          this.list_riskIndicators[i] = {}
          this.list_riskIndicators[i]['0'] = val
        })
        this._list_riskIndicators = deepClone(this.list_riskIndicators)
        this.getIndexRiskByIndexTypeAndTime(this.formData.types)
      })
    },
    // 风险指标 对比
    getIndexRiskByIndexTypeAndTime(indexType) {
      getIndexRiskByIndexTypeAndTime({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1],
      }).then(res => {
        console.log('收益风险指标 对比', res)
        const key_list = ['annualizedIncomeRate', 'annualFluctuationsRate', 'sharpeRate', 'maximumDrawdownRate', 'calmarRate', 'maxBackIncomDay']
        const obj = res.body
        this.add_column_list = this.add_column_list.slice(0, 1)
        this.list_riskIndicators = deepClone(this._list_riskIndicators)
        Object.keys(obj).forEach(key => {
          const element = obj[key]
          const header = this.contrastOptions_obj[key]
          this.list_riskIndicators.forEach((item, i) => {
            const index = Object.keys(item).length
            if(index!==0) {
              item[index] = element[key_list[i]]
            }else {
              item[1] = element[key_list[i]]
            }
          })
          this.add_column_list.push(header)
        })
      })
    },
    getStrategyByid(id) { // 详情
      return new Promise(resolve => {
        this.listLoading = true
        this.listLoading_riskIndicators = true
        this.listLoading_risk = true
        getInvestStrategyDetial({
          id,
          investId: this.investId
        }).then(res => {
          this.listLoading = false
          console.log('策略详情', res)
          this.strategy_dels = res.body
          const start_date = parseTime(res.body.investDetial.investStarttime, '{y}-{m}-{d}')
          const end_date = res.body.investDetial.investEndtime ? parseTime(res.body.investDetial.investEndtime) : parseTime(new Date())
          this.chart_date = [start_date, end_date]
          this.formData.types.push(res.body.investDetial.investIndex)
          resolve(this.chart_date)
          this.getriskIndicators() // 风险指标
          if(this.formData.types.length) {
            Promise.all([this.getnetWorthLine(start_date, end_date), this.findMaxDown(start_date, end_date)]).then(() => {})
          }else {
            this.getnetWorthLine(start_date, end_date) // 历史走势图 数据
            this.findMaxDown(start_date, end_date) // 历史走势图-风险概括 数据
          }
        })
      })
    },
    // 指数月度表现
    monthContrastHandle(indexType) {
      getMonthlyIndex({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1]
      }).then(res => {
        console.log('指数月度表现', res)
        Object.keys(res.body).forEach(key => {
          const items = res.body[key]
          items.forEach(item => {
            if(item.indexTime) {
              item.month = Number(item.indexTime.slice(5))
            }else {
              item.month = 13
            }
            item.monthIncrease = item.indexGrowthRate==null ? null : Number(item.indexGrowthRate)
          })
        })
        const list = Object.keys(res.body).map(function(i) { return res.body[i] })
        const new_list = deepClone(list)
        list.forEach((items, index) => {
          if(items.length<13) {
            new_list[index] = []
            const year = items[0].year
            for(let i=0; i<13; i++) {
              if(items[i]&&items[i].month != i+1) {
                if(!new_list[index][i]) {
                  new_list[index][i] = {
                    year: items[i].year
                  }
                }
                new_list[index][items[i].month-1] = deepClone(items[i])
              }else if(!new_list[index][i]) {
                if(items[i]&&items[i].month == i+1) {
                  new_list[index][items[i].month-1] = deepClone(items[i])
                }else {
                  new_list[index][i] = {
                    year
                  }
                }
              }
            }
          }
        })
        this.list_showMonth = deepClone(this._list_showMonth)
        new_list.forEach(element => {
          this.list_showMonth.forEach((item, i) => {
            if(element[0].year == item[0].year) {
              this.list_showMonth.splice(i+1, 0, element)
            }
          })
        })
      })
      if(this.month_contrast) this.findTimeScopeGrowth(this.month_contrast)
    },
    // 历史月度表现
    getMonthNetWorth(id) {
      this.listLoading_monthNetWorth = true
      getMonthlyIncrease({
        id
      }).then(res => {
        this.listLoading_monthNetWorth = false
        const list = Object.keys(res.body).map(function(i) { return res.body[i] })
        const new_list = deepClone(list)
        console.log('历史月度表现', list)
        list.forEach((items, index) => {
          if(items.length<13) {
            new_list[index] = []
            const year = items[0].year
            for(let i=0; i<13; i++) {
              if(items[i]&&items[i].month != i+1) {
                if(!new_list[index][i]) {
                  new_list[index][i] = {
                    year: items[i].year
                  }
                }
                new_list[index][items[i].month-1] = deepClone(items[i])
              }else if(!new_list[index][i]) {
                if(items[i]&&items[i].month == i+1) {
                  new_list[index][items[i].month-1] = deepClone(items[i])
                }else {
                  new_list[index][i] = {
                    year
                  }
                }
              }
            }
          }
        })
        this.list_showMonth = new_list
        this._list_showMonth = deepClone(new_list)
        console.log('历史月度表现 修改........', this.list_showMonth)
      })
    },
    getnetWorthLine(startTime, endTime) {
      findRealityInvestNetWorthByStrategyId({
        id: this.strategyId,
        startTime,
        endTime,
      }).then(res => {
        console.log('净值曲线', res)
        this.list_netWorthLine = res.body
      })
    },
    findMaxDown(startTime, endTime) {
      this.listLoading_risk = true
      findMaxDown({
        id: this.strategyId,
        startTime,
        endTime,
      }).then(res => {
        this.listLoading_risk = false
        console.log('风险概览', res)
        this.list_risk_chart = res.body
      })
    },
    getNetWorth() {
      this.listLoading_netWorth = true
      findNetWorthByPage({
        investId: this.investId,
        userId: this.userId,
        id: this.strategyId,
        ...this.listQuery
      }).then(res => {
        if(res.code == 0) {
          this.listLoading_netWorth = false
          console.log('历史净值', res)
          this.list_netWorth = res.body.list
          this.total_netWorth = res.body.total
        }
      })
    },
    // 对比指标 选择树
    queryAllIndexType() {
      queryAllIndexType().then(res => {
        console.log('对比指标', res)
        res.body.forEach((item, i) => {
          res.body[i].typeName = item.modelName
        })
        this.contrastOptions = res.body
        res.body.forEach(items => {
          items.lists.forEach(item => {
            this.contrastOptions_obj[item.id] = item.typeName
          })
        })
        this.formData.types.forEach(item => {
          this.one_contrastOptions_list.push({
            id: item,
            name: this.contrastOptions_obj[item]
          })
        })
        this.month_contrast = this.formData.types[0]
        setTimeout(() => {
          this.monthContrastHandle(this.month_contrast)
        }, 500)
      })
    },
    // 收益分布
    getMonthNetWorthLine(id) {
      monthlyNetworthHistogram({
        id
      }).then(res => {
        console.log('收益分布', res)
        this.list_monthNetWorthLine = res.body
      })
    },
    headTail(list) {
      list.unshift(list[list.length-1])
      list.splice(list.length-1, 1)
    },
    // 收益分布 列表
    findNetWorthExtendByStrategyId2(id) {
      this.findNetWorthExtendByStrategyId2_loading = true
      findNetWorthBySegment({
        id
      }).then(res => {
        console.log('收益分布 列表', res)
        this.headTail(res.body)
        this.list_showMonth_profit = res.body
        setTimeout(() => {
          this.findTimeScopeGrowth(this.month_contrast)
        }, 100)
      })
    },
    findTimeScopeGrowth(indexType) {
      findTimeScopeGrowth({
        indexType,
        startTime: this.chart_date[0],
        endTime: this.chart_date[1],
      }).then(res => {
        console.log('对比指数 收益分布 列表', res)
        this.headTail(res.body)
        this.findNetWorthExtendByStrategyId2_loading = false
        this.list_showMonth_profit.forEach((item, i) => {
          item.growth = res.body[i].growth
        })
        this.list_showMonth_key++
      })
    },
    // 月度回报
    getMonthNetWorthDistributed(id) {
      getMonthInvestNetWorthDistributed({
        id
      }).then(res => {
        console.log('月度回报', res)
        this.list_monthNetWorthDistributed = res.body
      })
    },
    // 月度回报 列表
    getMonthNetWorthDetial(id) {
      this.getMonthNetWorthDetial_loading = true
      getInvestMonthNetWorthDetial({
        id,
        ...this.monthNetWorthDetial_listQuery
      }).then(res => {
        console.log('月度回报 列表', res)
        this.getMonthNetWorthDetial_loading = false
        this.list_table_getMonthNetWorthDetial = res.list
        this.monthNetWorthDetial_total = res.total
      })
    },
    // 保存应用
    saveParamsHandle() {
      saveUserSelectType({
        userId: this.userId,
        id: this.strategyId,
        ...this.formData
      }).then(() => {
        this.findIndexByIndexTypeAndIndexTime(this.chart_date[0], this.chart_date[1], this.formData.types)
        this.findIndexMaxDown(this.chart_date[0], this.chart_date[1], this.formData.types)
        this.getIndexRiskByIndexTypeAndTime(this.formData.types)
      })
    },
    resetForm(ref) {
      this.$refs[ref].resetFields()
      this.contrastIndex_obj = {}
      this.contrastIndexRisk_obj = {}
    },
    refresh() {
      location.reload()
    },
    // 获取对比指标历史收益走势
    findIndexByIndexTypeAndIndexTime(startTime, endTime, indexType) {
      findIndexByIndexTypeAndIndexTime({
        startTime,
        endTime,
        indexType
      }).then(res => {
        console.log('获取对比指标历史收益走势', res)
        this.contrastIndex_obj = {}
        Object.keys(res.body).forEach(key => {
          const item = res.body[key]
          const _key = this.contrastOptions_obj[key]
          this.contrastIndex_obj[_key] = item
        })
      })
    },
    // 对比指数风险概览 （指数的最大回撤）
    findIndexMaxDown(startTime, endTime, indexType) {
      findIndexMaxDown({
        startTime,
        endTime,
        indexType
      }).then(res => {
        console.log('获取对比指数风险概览', res)
        this.contrastIndexRisk_obj = {}
        Object.keys(res.body).forEach(key => {
          const item = res.body[key]
          const _key = this.contrastOptions_obj[key]
          this.contrastIndexRisk_obj[_key] = item
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.strategyAnalyse-page {
  position: relative;
  .column {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
    margin-top: 30px;
    cursor: pointer;
    user-select: none;
    .el-icon { color: #4F95DD; font-weight: bold; margin-left: 6px; }
    .openChunk { transform: rotate(90deg); }
    &::before {
      display: inline-block;
      content: '';
      width: 6px;
      height: 26px;
      background: #42b983;
      margin-right: 6px;
    }
  }
  .head {
    padding: 15px 15px 0;
    border: 1px solid #e1e0e0;
    font-size: 14px;
    .redFont { color: #c00; }
    .fromLine {
      display: flex;
      line-height: 24px;
      .label { width: 80px; text-align: right; }
      // .fromLine-content {}
    }
    .chunk {
      display: flex;
      > div:nth-of-type(1) { width: 28%; }
      > div:nth-of-type(2) { width: 22%; }
      > div:nth-of-type(3) { width: 22%; }
      > div:nth-of-type(4) { width: 28%; }
      .chunk-strategyType {
        width: 100% !important; height: 100%;
        display: flex;
        > div { flex: 1; }
        > div + div {
          border-left: 1px dashed #e1e0e0;
          margin-left: 20px;
        }
        .netWorth-strategyType {
          justify-content: space-around;
        }
      }
      .history-strategyType {
        div {
          display: flex;align-items: center;
          .label {
            justify-content: flex-end;
          }
        }
        & + .history-strategyType {
          margin-left: 20px;
        }
      }
    }
    .chunk + .chunk { border-top: 1px dashed #e1e0e0; }
    .title {
      height: 84px;
      .product {
        h3 {font-size: 22px;}
        .tips {
          margin-top: 30px;
          .tip {
            border: 1px solid #3D71AE;
            color: #3D71AE;
            padding: 3px 6px;
            & + .tip { margin-left: 6px; }
          }
        }
      }
      // .info {
      //   padding-left: 7%;
      // }
    }
    .title-center { line-height: 35px; }
    .data {
      height: 114px;
      padding: 10px 0;
      > div + div {
        border-left: 1px dashed #e1e0e0;
        margin-left: 20px;
      }
      .netWorth {
        display: flex;
        justify-content: space-between;
        .label { width: 100px; text-align: right; }
        .netWorth1 {
          display: flex; flex-direction: column; justify-content: center; align-items: center;
          .num { font-size: 32px; line-height: 38px; color: #c00; }
        }
        .netWorth2 { display: flex; flex-direction: column; justify-content: center; align-items: center; div { line-height: 36px; } }
      }
      .profit, .history {
        > div {line-height: 32px;}
        > div {
          display: flex; justify-content: space-around;
          span {width: 33.33%;text-align: center;}
        }
      }
      .other {
        display: flex;
        > div {display: flex; flex-direction: column; justify-content: space-around;}
      }
    }
    .operation {
      height: 80px;
      display: flex;
      align-items: center;
    }
  }
  .from-alignCenter {
    ::v-deep .el-form{
      .el-form-item { margin-bottom: 0; }
    }
  }
  .title {
    .sub-title {
      display: flex;
      margin-top: 20px;
      span + span::before {
        display: inline-block;
        content: '|';
        padding: 0 20px;
      }
    }
  }
  .showHistoryChunk {
    display: flex;
    .historyChunk {
      // flex: 1;
      width: 50%;
      &:nth-child(1) { width: 100%; }
    }
  }
  .scrollCard {
    width: calc(100% - #{$sideBarWidth} - 80px);
    height: 80px;
    font-size: 14px;
    background: #FFF;
    z-index: 668;
    border: 1px solid #e1e0e0;
    display: flex;
    align-items: center;
    position: fixed;
    top: 0;
    padding-left: 15px;
  }
  .line {
    display: flex;
    .showMonth {
      display: flex;
      align-items: center;
      & + .showMonth {margin-left: 15px;}
      .round {width: 10px;height: 10px;border-radius: 50%;margin-right: 5px;}
      .round1 {background: #e16757;}
      .round2 {background: #78b2eb;}
    }
  }
  .month-chartContent {
    display: flex;
    .mChunk {width: 50%;}
  }
  ::v-deep .el-table {
    .title-row {
      background: #dcedff !important;
    }
    .cell-row-0 {
      background: #FFF7F7 !important;
    }
    .cell-row-1 {
      background: #FFFCF5 !important;
    }
    .cell-row-2 {
      background: #FFFBFD !important;
    }
    .cell-row-3 {
      background: #FAFFFB !important;
    }
    .cell-row-4 {
      background: #FFFCFC !important;
    }
    .cell-row-5 {
      background: #F9FDFF !important;
    }
    .cell-row-6 {
      background: #FDFBFE !important;
    }

    // 历史月度表现
    .showMonthyearBorder0 {
      border-right: 2px solid #e16757;
    }
    .showMonthyearBorder1 {
      border-right: 2px solid #78b2eb;
    }
  }

  .circular {
    width: 8px;
    height: 8px;
    display: inline-block;
    border-radius: 50%;

  }
}
</style>



